/*
 * @Author: 刘晟勇
 * @Date: 2021-10-12 18:52:24
 * @LastEditTime: 2021-10-23 09:55:35
 * @Description: file content
 */
import Vue from 'vue'
import VueRouter from 'vue-router'


// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}


// 懒加载组件
const home = () => import('@/views/home/home.vue')
const category = () => import('@/views/category/category.vue')
const shopcart = () => import('@/views/shopcart/shopcart.vue')
const user = () => import('@/views/user/user.vue')
const ProductList = () => import('@/views/product/product-list.vue')
const ProductDetail = () => import('@/views/product/product-detail.vue')
const login = () => import('@/views/login/login.vue')
const register = () => import('@/views/login/register.vue')
const profile = () => import('@/views/user/profile.vue')
const proxy = () => import('@/views/login/proxy.vue')

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    component: home,
    meta: {
      index: 1
    },
  },
  {
    path: '/category',
    component: category,
    meta: {
      index: 2
    },
  },
  {
    path: '/shopcart',
    component: shopcart,
    meta: {
      isAuth: true,
      index: 3
    }
  },
  {
    path: '/user',
    component: user,
    meta: {
      isAuth: true,
      index: 4
    }
  },
  {
    name: 'Product-list',
    path: '/Product-list/:id',
    component: ProductList,
    meta: {
      index: 2
    },
  },
  {
    name: 'product-detail',
    path: '/product-detail/:id',
    component: ProductDetail,
    meta: {
      index: 3
    },
  },
  {
    path: '/login',
    component: login,
    meta: {
      index: 5
    },
    beforeEnter: (to, from, next) => {
      if (sessionStorage.getItem('isLogin') === 'true') {
        return next('/')
      } else {
        return next()
      }
    }
  },
  {
    path: '/register',
    component: register,
    meta: {
      index: 6
    }
  },
  {
    path: '/profile',
    component: profile,
    meta: {
      index: 5
    }
  },
  {
    path: '/proxy',
    component: proxy,
    meta: {
      index: 5
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.isAuth) {
    if (sessionStorage.getItem('isLogin') === 'true') {
      return next()
    } else {
      return next({
        path: '/login',
        query: {
          toPath: to.fullPath
        }
      })
    }
  } else {
    return next()
  }
})

export default router